<?php
define('UPLOAD_FILE_PATH', './uploads');

class Uploader {
	// 检测文件输入中的内容是否为多文件上传/单文件上传
	// 多文件上传，函数返回true，单文件上传函数返回false
	private function is_multiple($fileInput){
		if(is_array($fileInput['name']))return true;
		else return false;
	}
	
	// 单文件上传
	private function normal_upload($fileInput){
		if(!$fileInput){
			throw new Exception("没有文件输入！");
		}
		$fileName = $fileInput['name'];
		$tmpFileName = $fileInput['tmp_name'];
		$error = $fileInput['error'];
	
		$this->fileSaveToLocal($fileName, $tmpFileName, $error);
	}
	// 多文件上传
	private function multiple_upload($fileInput){
		if(!$fileInput){
			throw new Exception("没有文件输入！");
		}
		for($i = 0; $i < count($fileInput['name']); ++$i){
			$fileName = $fileInput['name'][$i];
			$tmpFileName = $fileInput['tmp_name'][$i];
			$error = $fileInput['error'][$i];
			$this->fileSaveToLocal($fileName, $tmpFileName, $error);
		}
	}
	// 根据文件名和临时文件名保存上传文件到指定的本地路径中去
	private function fileSaveToLocal($fileName, $tmpName, $error){
		switch($error){
			case 0:
				$dd = (date("Y-m-d-His"));
				$destination = UPLOAD_FILE_PATH . "/" . $dd . "/" . $fileName;
				if(!is_dir(UPLOAD_FILE_PATH."/".$dd)){
					mkdir(UPLOAD_FILE_PATH."/".$dd);
				}
				move_uploaded_file($tmpName, $destination);
				break;
			case 1:
				throw new Exception("上传附件超过了php.ini中upload_max_filesize选项限制的值！");
				break;
			case 2:
				throw new Exception("上传附件的大小超过了form表单MAX_FILE_SIZE选项指定的值！");
				break;
			case 3:
				throw new Exception("附件只有部分被上传！");
				break;
			case 4:
				throw new Exception("没有选择上传附件！");
				break;
		}
	}
	
	public function upload($fileObj){
		foreach($fileObj as $fileInput){
			if($this->is_multiple($fileInput)){
				// 多文件上传
				$this->multiple_upload($fileInput);
			}else{
				// 单文件上传
				$this->normal_upload($fileInput);
			}
		}
	}
}